/**
 * HMI 表格数据管理 Composable
 */
import { ref, computed, reactive, watchEffect, onUnmounted } from "vue";
import type { HmiTableRow, HmiColumnConfig, ChangeRecord, HmiBatchUpdateConfig } from "../types";
import { useComApiTableStore, useSettingZoneStore } from "@/store";
import { useBaseTableData, DATA_STATUS as BASE_STATUS } from "@/components/HmiCommon/composables/useBaseTableData";

// 定义一个枚举表示数据状态，等待、成功、错误、无数据等
export enum DATA_STATUS {
  WAITING = BASE_STATUS.WAITING,
  SUCCESS = BASE_STATUS.SUCCESS,
  ERROR = BASE_STATUS.ERROR,
  NODATA = BASE_STATUS.NODATA,
  EDITED = "edited",
}

export function useHmiTableData(config: HmiBatchUpdateConfig) {
  const hmiApiTableStore = useComApiTableStore();
  const settingZoneStore = useSettingZoneStore();

  // 自动刷新相关（提前声明，用于 fetchGuard 与 Base 联动）
  const autoRefreshEnabled = ref(false);
  const autoRefreshInterval = ref<number | null>(null);
  const AUTO_REFRESH_INTERVAL = 1000; // 1秒刷新间隔

  // 基座：统一获取/排序/前端切片/刷新
  const base = useBaseTableData<HmiTableRow>({
    apiPath: computed(() => config.apiPath),
    pageSize: computed(() => config.pagination?.pageSize || 10),
    group: computed(() => config.group),
    orderByKey: computed(() => config.orderByKey),
    showSettingZone: computed(() => !!config.showSettingZone),
    displayZone: computed(() => settingZoneStore.displayZone),
    fetchGuard: () => autoRefreshEnabled.value,
    formatRow: (item, index) => {
      const originalValue = (item as any)[config.valueKey];
      return {
        ...(item as any),
        _index: index,
        newValue: cloneValue(originalValue),
        _originalValue: cloneValue(originalValue),
        _hasChanged: false,
      } as HmiTableRow;
    },
  });
  const tableData = base.tableData;
  const loading = base.loading;
  const total = base.total;
  const changeHistory = reactive(new Map<string | number, ChangeRecord>());

  // 分页参数
  const pagination = base.pagination;

  // 计算属性
  const hasChanges = computed(() => changeHistory.size > 0);
  const changes = computed(() => Array.from(changeHistory.values()));

  // 失败冷却标志（Base 已处理 loading/状态，此处不再需要专门冷却标志）

  // 数据状态（映射 Base 的字符串状态到本枚举）
  const data_status = ref<DATA_STATUS>(DATA_STATUS.WAITING);

  // 数据格式化逻辑由 Base 的 formatRow 提供

  // 安全的值克隆
  function cloneValue(value: any): any {
    if (value === null || value === undefined) return value;
    if (typeof value === "object") {
      try {
        return JSON.parse(JSON.stringify(value));
      } catch {
        return value;
      }
    }
    return value;
  }

  // 设置自动刷新
  function setAutoRefresh(enabled: boolean) {
    autoRefreshEnabled.value = enabled;
    
    if (enabled) {
      // 启动自动刷新
      if (!autoRefreshInterval.value) {
        autoRefreshInterval.value = window.setInterval(() => {
          if (!loading.value && autoRefreshEnabled.value) {
            console.log("Auto refreshing data...");
            fetchData().catch(error => {
              console.error('Auto refresh failed:', error);
            });
          }
        }, AUTO_REFRESH_INTERVAL);
      }
    } else {
      // 停止自动刷新
      if (autoRefreshInterval.value) {
        clearInterval(autoRefreshInterval.value);
        autoRefreshInterval.value = null;
      }
    }
  }

  // 清理自动刷新
  function cleanupAutoRefresh() {
    if (autoRefreshInterval.value) {
      clearInterval(autoRefreshInterval.value);
      autoRefreshInterval.value = null;
    }
  }
  async function fetchData(_force = false) {
    if (config.showSettingZone && !settingZoneStore.isReady) {
      // 等待定值区初始化
      return;
    }
    console.log("useHmiTableData: fetchData called, force =", _force);
    const res = await base.fetchData();
    data_status.value = base.dataStatus.value as unknown as DATA_STATUS;
    changeHistory.clear();
    return res;
  }

  // 分页变更时，优先使用前端切片，避免重复请求
  async function handlePaginationChange() {
    return await base.handlePaginationChange();
  }

  // 强制刷新：不触发 watchEffect 的二次请求，直接强制拉取
  async function refreshData() {
    const res = await base.refreshData();
    return res as any;
  }

  // 处理值变更
  function handleValueChange(row: HmiTableRow, column: HmiColumnConfig) {
    const rowId = row[config.idKey];
    const newValue = row.newValue;
    const originalValue = row._originalValue;

    // 比较值是否真的发生了变化
    const hasChanged = !isEqual(newValue, originalValue);
    row._hasChanged = hasChanged;

    if (hasChanged) {
      changeHistory.set(rowId, {
        id: rowId,
        oldValue: cloneValue(originalValue),
        newValue: cloneValue(newValue),
        column: column.key,
      });
    } else {
      changeHistory.delete(rowId);
    }
  }

  // 值比较
  function isEqual(a: any, b: any): boolean {
    if (a === b) return true;
    if (typeof a !== typeof b) return false;
    if (typeof a === "object" && a !== null && b !== null) {
      return JSON.stringify(a) === JSON.stringify(b);
    }
    return false;
  }

  // 将首字母大写，其他小写
  function capitalizeFirstLetter(str: string) {
    if (!str) return ""; // 处理空字符串或非字符串情况
    str = str.toString(); // 确保是字符串类型
    return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
  }

  // updateBodyKey 处理上传的其他 key 的值映射，不区分大小写
  /** 例如 key： type， 返回  row[type] 或 row[Type]，哪个有值返回哪个 */
  /** 将 key 转换为 首字符大写，其他小写 */
  function getUpdateBody(row: HmiTableRow, key: string) {
    const lowerCaseKey = key.toLowerCase();
    const capitalizedKey = capitalizeFirstLetter(key);
    // console.log(row, " : ", capitalizedKey, " : ", lowerCaseKey);
    return row[capitalizedKey] || row[lowerCaseKey];
  }

  // 保存变更
  async function saveChanges() {
    if (!hasChanges.value) return;
    if (loading.value) return;

    loading.value = true;
    try {
      console.log("config:", config);
      const changesData = Array.from(changeHistory.entries()).map(([id, change]) => {
        /** 带 updateBodyKey */
        if (
          config.updateBodyKey &&
          Array.isArray(config.updateBodyKey) &&
          config.updateBodyKey.length > 0
        ) {
          // const row = tableData.value[index];
          const row = tableData.value.find((item) => item[config.idKey] === id);
          if (!row) {
            console.warn(`未找到ID为 ${id} 的行数据`);
            return {
              [config.updateIdKey]: id,
              [config.updateValueKey]: change.newValue,
              ...config.updateBodyConfig,
            };
          }
          const keyBody = config.updateBodyKey.reduce(
            (acc, key) => ({ ...acc, [key.toLowerCase()]: getUpdateBody(row, key) }),
            {}
          );
          // console.log(keyBody, " : ", getUpdateBody(row, "Type"));
          return {
            [config.updateIdKey]: id,
            [config.updateValueKey]: change.newValue,
            ...keyBody,
            ...config.updateBodyConfig,
          };
        } else {
          /** 不带 updateBodyKey */
          console.log("post body", {
            [config.updateIdKey]: id,
            [config.updateValueKey]: change.newValue,
            ...config.updateBodyConfig,
          });
          console.log("post body config", config.updateBodyConfig);
          return {
            [config.updateIdKey]: id,
            [config.updateValueKey]: change.newValue,
            ...config.updateBodyConfig,
          };
        }
      });
      let apiUrl = "";
      /**
       * 1. displayZone === undefined 则 使用 config.updateApi
       * 2. displayZone 有值，则使用 config.updateApi +  /${displayZone}
       *  */
      if (config.showSettingZone && settingZoneStore.displayZone) {
        apiUrl = (config.updateApi || config.apiPath) + `/${settingZoneStore.displayZone}`;
      } else {
        apiUrl = config.updateApi || config.apiPath;
      }
      await hmiApiTableStore.batchUpdate(apiUrl, changesData);

      // 更新原始值
      tableData.value.forEach((row) => {
        if (row._hasChanged) {
          row._originalValue = cloneValue(row.newValue);
          row._hasChanged = false;
        }
      });
      data_status.value = DATA_STATUS.EDITED;
      changeHistory.clear();
      return changesData;
    } catch (error) {
      console.error("保存失败:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  }

  // 自动设置
  async function autoSet() {
    if (!config.autoSetApi) return;
    const postBody = config.updateBodyConfig;
    const res = await hmiApiTableStore.autoChannelSet(config.autoSetApi, postBody);
    return res.status;
  }

  // 重置变更
  function resetChanges() {
    tableData.value.forEach((row) => {
      if (row._hasChanged) {
        row.newValue = cloneValue(row._originalValue);
        row._hasChanged = false;
      }
    });
    changeHistory.clear();
  }

  // 监听 settingZoneStore 的初始化状态
  watchEffect(() => {
    console.log("useHmiTableData: settingZoneStore.isReady =", settingZoneStore.isReady);
    if (config.showSettingZone) {
      // 当 settingZoneStore 初始化完成时，自动获取数据
      if (settingZoneStore.isReady) {
        console.log("settingZoneStore 已初始化，开始获取数据");
        fetchData();
      }
    } else {
      // 不需要定值区时，直接获取数据
      console.log("不需要定值区，开始获取数据");
      fetchData();
    }
  });

  return {
    // 状态
    tableData,
    loading,
    total,
    pagination,

    // 计算属性
    hasChanges,
    changes,
    autoRefreshEnabled,

    // 方法
    fetchData,
    handleValueChange,
    saveChanges,
    autoSet,
    resetChanges,
    setAutoRefresh,
    cleanupAutoRefresh,
    handlePaginationChange,
    refreshData,
  };
}
